package org.dut.community.controller;

import lombok.extern.slf4j.Slf4j;
import org.dut.community.entity.Event;
import org.dut.community.entity.Page;
import org.dut.community.entity.User;
import org.dut.community.event.EventProducer;
import org.dut.community.service.FollowService;
import org.dut.community.service.UserService;
import org.dut.community.util.CommunityConstant;
import org.dut.community.util.CommunityUtil;
import org.dut.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.dut.community.util.CommunityConstant.ENTITY_TYPE_USER;


@Controller
public class FollowController implements CommunityConstant {
    @Autowired
    private FollowService followService;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private UserService userService;
    @Autowired
    private EventProducer eventProducer;


    /**
     * 关注
     * @param entityType 实体类型
     * @param entityId 实体id
     * @return
     */
    @ResponseBody
    @RequestMapping(path = "/follow",method = RequestMethod.POST)
    public String follow(int entityType,int entityId){
        User user = hostHolder.getUser();
        if(user == null){
            return CommunityUtil.getJSONString(403,"您还没有登录!");
        }
        followService.follow(user.getId(),entityType,entityId);

        Map<String,Object> map = new HashMap<>();
        map.put("followerCount",followService.findFollowerCount(ENTITY_TYPE_USER,entityId));

        // 事件发布
        Event event = Event.builder()
                .topic(TOPIC_FOLLOW)
                .userId(user.getId())
                .entityType(entityType)
                .entityId(entityId)
                .entityUserId(entityId)
                .build();
        eventProducer.fireEvent(event);


        return CommunityUtil.getJSONString(0,"关注成功!",map);
    }

    /**
     * 取消关注
     * @param entityType 实体类型
     * @param entityId 实体id
     * @return
     */
    @ResponseBody
    @RequestMapping(path = "/unfollow",method = RequestMethod.POST)
    public String unfollow(int entityType,int entityId){
        User user = hostHolder.getUser();
        if(user == null){
            return CommunityUtil.getJSONString(403,"您还没有登录!");
        }
        followService.unfollow(user.getId(),entityType,entityId);
        Map<String,Object> map = new HashMap<>();
        map.put("followerCount",followService.findFollowerCount(ENTITY_TYPE_USER,entityId));
        return CommunityUtil.getJSONString(0,"取消关注成功!",map);
    }

    /**
     * 查询 用户关注的 followee，用于页面展示
     * @param userId 关注者
     */
    @RequestMapping(path = "/followees/{userId}",method = RequestMethod.GET)
    public String findFollowees(@PathVariable("userId") int userId, Page page, Model model) {
        User user = userService.findUserById(userId);
        if(user == null) {
            throw new IllegalArgumentException("该用户不存在!");
        }
        model.addAttribute("user",user);

        page.setLimit(5);
        page.setPath("/followees/"+userId);
        page.setRows((int)followService.findFolloweeCount(userId,ENTITY_TYPE_USER));

        // followee 列表
        List<Map<String,Object>> followees = new ArrayList<>();
        if(page.getRows() > 0) {
            followees = followService.findFollowees(userId,page.getOffset(),page.getLimit());
        }

        // 是否关注
        if(followees != null) {
            for(Map<String,Object> map : followees) {
                User u = (User) map.get("user");
                map.put("followed",followService.isFollowed(hostHolder.getUser().getId(),ENTITY_TYPE_USER,u.getId()));
            }
        }

        model.addAttribute("followees",followees);
        return "/site/followee";

    }

    /**
     * 查询 关注了该实体的 粉丝（follower），用于页面展示
     * @param userId 关注者
     */
    @RequestMapping(path = "/followers/{userId}",method = RequestMethod.GET)
    public String findFollowers(@PathVariable("userId") int userId, Page page, Model model) {
        User user = userService.findUserById(userId);
        if(user == null) {
            throw new IllegalArgumentException("该用户不存在!");
        }
        model.addAttribute("user",user);

        page.setLimit(5);
        page.setPath("/followers/"+userId);
        page.setRows((int)followService.findFollowerCount(ENTITY_TYPE_USER,userId));

        // follower 列表
        List<Map<String,Object>> followers = new ArrayList<>();
        if(page.getRows() > 0) {
            followers = followService.findFollowers(userId,page.getOffset(),page.getLimit());
        }

        // 是否关注
        if(followers != null) {
            for(Map<String,Object> map : followers) {
                User u = (User) map.get("user");
                map.put("followed",followService.isFollowed(hostHolder.getUser().getId(),ENTITY_TYPE_USER,u.getId()));
            }
        }

        model.addAttribute("followers",followers);
        return "/site/follower";
    }



}
